package com.gonsin.gnews.utils;

import com.gonsin.gnews.annotations.model.ConfigValueModel;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import javax.persistence.AttributeConverter;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

public class MapMapHandler implements TypeHandler<List<ConfigValueModel.ConfigItemPo>>, AttributeConverter<List<ConfigValueModel.ConfigItemPo>, String> {
    @Override
    public void setParameter(PreparedStatement ps, int i, List<ConfigValueModel.ConfigItemPo> parameter, JdbcType jdbcType) throws SQLException {
        if(parameter == null){
            ps.setString(i, "[]");
            return;
        }
        String json = new Gson().toJson(parameter);
        ps.setString(i, json);
    }

    @Override
    public List<ConfigValueModel.ConfigItemPo> getResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        if(StringUtils.isEmpty(json)){
            return new ArrayList<>();
        }
        return new Gson().fromJson(json, new TypeToken<List<ConfigValueModel.ConfigItemPo>>(){}.getType());
    }

    @Override
    public List<ConfigValueModel.ConfigItemPo> getResult(ResultSet rs, int columnIndex) throws SQLException {
        return null;
    }

    @Override
    public List<ConfigValueModel.ConfigItemPo> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        return null;
    }

    @Override
    public String convertToDatabaseColumn(List<ConfigValueModel.ConfigItemPo> attribute) {
        if(attribute == null){
            return "[]";
        }
        String json = new Gson().toJson(attribute);
        return json;
    }

    @Override
    public List<ConfigValueModel.ConfigItemPo> convertToEntityAttribute(String dbData) {
        if(StringUtils.isEmpty(dbData)){
            return new ArrayList<>();
        }
        return new Gson().fromJson(dbData, new TypeToken<Set<ConfigValueModel.ConfigItemPo>>(){}.getType());
    }
}
